package com.manor.common.activity

import android.app.Activity
import android.app.ActivityOptions
import android.app.AlertDialog
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.content.res.Configuration
import android.content.res.Resources
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.text.TextUtils
import android.view.View
import android.view.WindowManager
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import com.blankj.utilcode.util.ClickUtils
import com.blankj.utilcode.util.ToastUtils
import com.manor.common.R
import com.manor.common.dialog.WaitingDialog
import com.manor.common.http.HttpClient
import com.manor.common.interfaces.LifeCycleListener
import com.manor.common.utils.ActivityManager
import com.manor.common.utils.ClickUtil
import com.umeng.analytics.MobclickAgent
import com.yanzhenjie.permission.AndPermission
import com.yanzhenjie.permission.runtime.Permission
import kotlinx.android.synthetic.main.lyb_include_base_top.*
import java.util.*
import kotlin.collections.ArrayList

/**
 * Created by cxf on 2017/8/3.
 */
abstract class AbsActivity : AppCompatActivity(), View.OnClickListener {
    private var mTag: String? = null
    lateinit var mContext: Context
    private var mLifeCycleListeners: ArrayList<LifeCycleListener> = arrayListOf()
    private var handler: Handler? = null
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mTag = this.javaClass.simpleName
        setStatusBar()
        setContentView(getLayoutId())
        mContext = this
        mLifeCycleListeners = ArrayList()
        main(savedInstanceState)
        for (listener in mLifeCycleListeners) {
            listener.onCreate()
        }
        ActivityManager.getInstance().addActivity(this)
    }

    /**
     * 重写getResources()方法，让APP的字体不受系统设置字体大小影响
     */
    override fun getResources(): Resources {
        val res = super.getResources()
        val config = Configuration()
        config.setToDefaults()
        res.updateConfiguration(config, res.displayMetrics)
        return res
    }

    protected abstract fun getLayoutId(): Int
    protected open fun main(savedInstanceState: Bundle?) {
        main()
    }

    protected open fun main() {}
    protected open val isStatusBarWhite: Boolean
        protected get() = false

    protected fun setTitle(title: String?) {
        val titleView = findViewById<View>(R.id.titleView) as TextView
        if (titleView != null) {
            titleView.text = title
        }
    }

    fun backClick(v: View) {
        if (v.id == R.id.btn_back) {
            onBackPressed()
        }
    }

    var alertDialog: AlertDialog? = null

    /**
     * Display setting dialog.
     */
    fun showSettingDialog(context: Context, msg: String, requestCode: Int) {
        if (null == alertDialog) {
            alertDialog = AlertDialog.Builder(context).setCancelable(false)
                    .setTitle(context.resources.getString(R.string.permissions_title))
                    .setMessage(msg)
                    .setPositiveButton(R.string.permissions_setting) { dialog, which -> setPermission(requestCode) }
                    .show()
            return
        }
        if (null != alertDialog && !alertDialog!!.isShowing) {
            alertDialog = AlertDialog.Builder(context).setCancelable(false)
                    .setTitle(context.resources.getString(R.string.permissions_title))
                    .setMessage(msg)
                    .setPositiveButton(R.string.permissions_setting) { dialog, which -> setPermission(requestCode) }
                    .show()
        }
    }

    private fun setPermission(requestCode: Int) {
        AndPermission.with(this).runtime().setting().start(requestCode)
    }

    protected fun canClick(): Boolean {
        return ClickUtil.canClick()
    }

    private var mWaitingDialog: WaitingDialog? = null

    /**
     * 显示等待对话框
     *
     * @param cancelable
     */
    fun showWaitingDialog(cancelable: Boolean = false) {
        if (this.isFinishing) return
        if (mWaitingDialog == null) {
            mWaitingDialog = WaitingDialog.newDialog(this)
        }
        if (mWaitingDialog!!.isShowing) {
            mWaitingDialog!!.dismiss()
        }
        mWaitingDialog!!.setCancelable(cancelable)
        mWaitingDialog!!.show()
        if (handler == null) {
            handler = Handler(Looper.getMainLooper())
        }
        handler!!.postDelayed({ dismissWaitingDialog() }, HttpClient.TIMEOUT.toLong())
    }

    /**
     * 取消等待对话框
     */
    fun dismissWaitingDialog() {
//        if (this.isFinishing())
//            return;
        if (mWaitingDialog != null && mWaitingDialog!!.isShowing) {
            mWaitingDialog!!.dismiss()
        }
        if (handler != null) handler!!.removeCallbacksAndMessages(null)
    }

    /**
     * 设置透明状态栏
     */
    private fun setStatusBar() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            val window = window
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS)
            if (isStatusBarWhite) {
                window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or View.SYSTEM_UI_FLAG_LAYOUT_STABLE
            } else {
                window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or View.SYSTEM_UI_FLAG_LAYOUT_STABLE or View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR
            }
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS)
            window.statusBarColor = 0
        }
    }

    override fun onDestroy() {
        dismissWaitingDialog()
        if (handler != null) handler!!.removeCallbacksAndMessages(null)
        if (mLifeCycleListeners != null) {
            for (listener in mLifeCycleListeners) {
                listener.onDestroy()
            }
            mLifeCycleListeners.clear()
        }
        ActivityManager.getInstance().removeActivity(this)
        super.onDestroy()
    }

    override fun onStart() {
        super.onStart()
        for (listener in mLifeCycleListeners) {
            listener.onStart()
        }
    }

    override fun onRestart() {
        super.onRestart()
        for (listener in mLifeCycleListeners) {
            listener.onReStart()
        }
    }

    override fun onResume() {
        super.onResume()
        for (listener in mLifeCycleListeners) {
            listener.onResume()
        }
        MobclickAgent.onResume(this)
    }

    override fun onPause() {
        super.onPause()
        if (mLifeCycleListeners != null) {
            for (listener in mLifeCycleListeners) {
                listener.onPause()
            }
        }
        MobclickAgent.onPause(this)
    }

    override fun onStop() {
        super.onStop()
        for (listener in mLifeCycleListeners) {
            listener.onStop()
        }
    }

    fun addLifeCycleListener(listener: LifeCycleListener?) {
        if (listener != null) {
            mLifeCycleListeners.add(listener)
        }
    }

    fun addAllLifeCycleListener(listeners: ArrayList<LifeCycleListener>?) {
        if (listeners != null) {
            mLifeCycleListeners.addAll(listeners)
        }
    }

    fun removeLifeCycleListener(listener: LifeCycleListener?) {
        mLifeCycleListeners.remove(listener)
    }

    fun startActivityWithOptions(activity: Activity?, intent: Intent?) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            var transitionActivity: ActivityOptions? = null
            transitionActivity = ActivityOptions.makeSceneTransitionAnimation(activity)
            mContext!!.startActivity(intent, transitionActivity.toBundle())
        } else {
            mContext!!.startActivity(intent)
        }
    }
    protected fun isActDestroy(act: Activity?): Boolean {
        return act == null || act.isFinishing || act.isDestroyed
    }


    companion object {
        @JvmStatic
        fun lacksPermission(mContexts: Context?, permission: String?): Boolean {
            return ContextCompat.checkSelfPermission(mContexts!!, permission!!) == PackageManager.PERMISSION_DENIED
        }
    }

    fun setClick(vararg views: View?){
        for (it in views){
            ClickUtils.applySingleDebouncing(it, 1000, this)
        }
    }
    protected fun setTopTitle(
            title: String, type: Int = 0, titleTvColor: Int = R.color.color_33,
            rightTitle: String = "", rightTvColor: Int = R.color.color_33,
            leftColor: Int = R.color.black, leftIv: Int = R.drawable.back_black,
            bgColor: Int = R.color.white,
            rightIv: Int = -1, lineShow: Boolean = true
    ) {
        mBackTv.setTextColor(ContextCompat.getColor(this, leftColor))
        mTitleBgLayout.setBackgroundColor(ContextCompat.getColor(this, bgColor))
        mBackIv.setImageResource(leftIv)
        setClick(mBackIv)

        if (!TextUtils.isEmpty(rightTitle)) {
            mRightTitleTv.text = rightTitle
            setClick(mRightTitleTv)
            mRightTitleTv.setTextColor(ContextCompat.getColor(this, rightTvColor))
            mRightTitleTv.visibility = View.VISIBLE
        }
        if (rightIv > 0) {
            mRightIv.setImageResource(rightIv)
            setClick(mRightIv)
            mRightIv.visibility = View.VISIBLE
        }
        when (type) {
            1 -> {
                mBackLayout.visibility = View.GONE
            }
        }
        setClick(mTitleTv)
        mTitleTv.text = title
        mTitleTv.setTextColor(ContextCompat.getColor(this, titleTvColor))
        if (lineShow) {
            mLineView.visibility = View.VISIBLE
        } else {
            mLineView.visibility = View.GONE
        }
    }
    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.mBackIv -> {
                finish()
            }
            R.id.mRightTitleTv -> {
            }
            R.id.mRightIv -> {
            }
            R.id.mTitleTv -> {
            }
        }
    }
    fun showT(msg: String?) {
        ToastUtils.showShort(msg)
    }

    fun callPhone(number: String?){
        AndPermission.with(this)
                .runtime()
                .permission(Permission.CALL_PHONE)
                .onGranted {
                    val intent = Intent(Intent.ACTION_DIAL)
                    val data = Uri.parse("tel:$number")
                    intent.data = data
                    startActivity(intent)
                }
                .onDenied { data ->
                }
                .start()
    }
}